/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package at.irian.demo.jsfatwork.view.page;

import at.irian.demo.jsfatwork.domain.Answer;
import at.irian.demo.jsfatwork.domain.Poll;
import at.irian.demo.jsfatwork.domain.User;
import at.irian.demo.jsfatwork.domain.Vote;
import at.irian.demo.jsfatwork.service.GroupService;
import at.irian.demo.jsfatwork.service.PollService;
import at.irian.demo.jsfatwork.service.VotingService;
import at.irian.demo.jsfatwork.view.PageBean;
import at.irian.demo.jsfatwork.view.security.UserHolder;
import org.apache.myfaces.orchestra.viewController.annotations.ViewController;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

/**
 * @author JSF@Work Project Team
 */
@PageBean
@Named("findPollPage")
@ViewController(viewIds = "/pages/polls/findPoll.xhtml")
public class FindPollPage extends AbstractPage
{
    @Inject
    private UserHolder userHolder;

    @Inject
    private PollService pollService;

    @Inject
    private GroupService groupService;

    @Inject
    private VotingService votingService;

    private Poll currentPoll;

    private List<Poll> openPolls;

    private String selectedGroupName;

    private List<Answer> possibleAnswers;

    private List<Answer> currentAnswers;

    private boolean showAnswers;

    private boolean showMyVotes;

    private List<Vote> myVotes;

    /*vote details*/
    private Vote currentVote;

    @Inject
    private VoteDetailPage voteDetailPage;


    @Override
    public void preparePageForRendering()
    {
        if (this.openPolls == null)
        {
            this.currentPoll = this.pollService.createNew();
            this.showMyVotes = true;

            User currentUser = this.userHolder.loadUser();
            this.openPolls = this.pollService.findOpenPolls(currentUser);
            filterPolls();
            this.myVotes = this.votingService.findVotes(currentUser);
        }
    }

    public void vote()
    {
        if (this.votingService.vote(this.userHolder.loadUser(), this.currentPoll, this.currentAnswers))
        {
            addMessage("confirmation_vote_submitted");
            cleanup();
            return;
        }

        addMessage("violation_vote_failed");
    }

    public String editVote()
    {
        this.voteDetailPage.setCurrentVote(currentVote);

        return "pages/polls/editVote";
    }

    /*
     * specific to PrimeFaces
     */
    public void setSelectedPoll(Object[] polls)
    {
        this.currentPoll = (Poll) polls[0]; //workaround
        this.showAnswers = true;
        this.showMyVotes = false;
        this.possibleAnswers = currentPoll.getAnswers();
    }

    public void setSelectedAnswers(Object[] currentAnswers)
    {
        this.currentAnswers = new ArrayList<Answer>();

        for (Object answer : currentAnswers) //workaround
        {
            this.currentAnswers.add((Answer) answer);
        }
    }

    /*
    * generated
    */
    public Poll getCurrentPoll()
    {
        return currentPoll;
    }

    public String getSelectedGroupName()
    {
        return selectedGroupName;
    }

    public void setSelectedGroupName(String selectedGroupName)
    {
        this.selectedGroupName = selectedGroupName;
    }

    public List<Poll> getOpenPolls()
    {
        return openPolls;
    }

    public boolean isShowAnswers()
    {
        return showAnswers;
    }

    public List<Answer> getPossibleAnswers()
    {
        return possibleAnswers;
    }

    public boolean isShowMyVotes()
    {
        return showMyVotes;
    }

    public List<Vote> getMyVotes()
    {
        return myVotes;
    }

    public void setCurrentVote(Vote currentVote)
    {
        this.currentVote = currentVote;
    }

    /*
     * common performance pitfall in combination with lazy loading
     * instead of the following code use a specialized query!!!
     */
    private void filterPolls()
    {
        Iterator<Poll> pollIterator = this.openPolls.iterator();

        User currentUser = this.userHolder.loadUser();

        while(pollIterator.hasNext())
        {
            if(isAlreadyVoted(pollIterator.next(), currentUser))
            {
                pollIterator.remove();
            }
        }
    }

    private boolean isAlreadyVoted(Poll poll, User currentUser)
    {
        for(Vote vote : poll.getVotes())
        {
            if(currentUser.getUserName().equals(vote.getVotedBy().getUserName()))
            {
                return true;
            }
        }
        return false;
    }
}